package com.pickgliss.light2d.texture
{
	import com.pickgliss.ds.BitmapLib;
	import com.pickgliss.light2d.display.LightImage;
	import com.pickgliss.light2d.display.LightStage;
	
	import flash.display.BitmapData;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.utils.Dictionary;
	public class TextureFactory
	{
		public static const IMAGE_TEXTURE:int = 0;
		public static const SPRITE_TEXTURE:int = 1;
		private static var _instance:TextureFactory;
		
		private var _nativeTextures:Dictionary = new Dictionary(true);

		public static function get Instance():TextureFactory
		{
			if(_instance == null)
			{
				_instance = new TextureFactory();
			}
			return _instance;
		}
		
		public function createTileTexture(textureId:String):ImageTexture
		{
			var nTex:Texture = getNativeTexture(textureId);
			if(nTex == null)return null;
			var bitmapData:BitmapData = BitmapLib.Instance.getBitmapData(textureId);
			var tex:ImageTexture = new ImageTexture();
			tex.texture = nTex;
			tex.textureWidth = bitmapData.width;
			tex.textureHeight = bitmapData.height;
			tex.textureId = textureId;
			return tex;
		}
		
		public function createSpriteTexture(textureId:String):ImageTexture
		{
			var nTex:Texture = getNativeTexture(textureId);
			if(nTex == null)return null;
			var bitmapData:BitmapData = BitmapLib.Instance.getBitmapData(textureId);
			var tex:SpriteTexture = new SpriteTexture();
			tex.texture = nTex;
			tex.textureWidth = bitmapData.width;
			tex.textureHeight = bitmapData.height;
			tex.textureId = textureId;
			return tex;
		}
		
		public function getNativeTexture(textureId:String):Texture
		{
			if(_nativeTextures.hasOwnProperty(textureId))
			{
				return _nativeTextures[textureId];
			}
			var bitmap:BitmapData = BitmapLib.Instance.getBitmapData(textureId);
			if(bitmap == null)return null;
			var texture:Texture = LightStage.context3D.createTexture(bitmap.width,bitmap.height,Context3DTextureFormat.BGRA,false);
			texture.uploadFromBitmapData(bitmap);
			_nativeTextures[textureId] = texture;
			return texture;
		}

		public function TextureFactory()
		{
		}
		
		public function createTexture(textureId:String,type:int):ImageTexture
		{
			if(type == IMAGE_TEXTURE)
			{
				return createTileTexture(textureId);
			}else if(type == SPRITE_TEXTURE)
			{
				return createSpriteTexture(textureId);
			}
			
			return null;
		}
	}
}